using System;
using System.Collections;
using System.Collections.Generic;

namespace BF
{
    public class ObjectPoolRoot : Singleton<ObjectPoolRoot>
    {
        private List<IPool> _pools = new List<IPool>();

        internal void RegisterPool<T>(ObjectPool<T> pool) where T : class, IRecycleable, new()
        {
            _pools.Add(pool);
        }

        internal void DeregisterPool<T>(ObjectPool<T> pool) where T : class, IRecycleable, new()
        {
            _pools.Remove(pool);
        }

        /// <summary>
        /// 删除池中所有缓存对象,不包括正在使用的
        /// </summary>
        public void ClearAllItemCache()
        {
            foreach (IPool pool in _pools)
            {
                pool.DestroyAllItemCache();
            }
        }

        public void ClearAllPool()
        {
            for (int i = _pools.Count - 1; i >= 0; i--)
            {
                _pools[i].Dispose();
            }
        }
    }

    public class ObjectPool<T> : BasePool<T> where T : class, IRecycleable, new()
    {
        private static ObjectPool<T> _instance;
        public static ObjectPool<T> instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ObjectPool<T>();
                }
                return _instance;
            }
        }


        /// <summary>
        /// 创建对象池
        /// 注：不需要时需要请方法Dispose(),不然占用的内存永远不会释放
        /// </summary>
        public ObjectPool()
        {
            ObjectPoolRoot.instance.RegisterPool(this);
        }

        public override void Dispose()
        {
            base.Dispose();
            if (_instance == this)
            {
                _instance = null;
            }
            ObjectPoolRoot.instance.DeregisterPool(this);
        }
    }
}
